/**
 *
 */
package com.evil.Answer;

import com.evil.Bean.AnswerOverItemBean;
import com.evil.DAO.AnswerDAO;
import com.evil.DAO.AnswerOverItemDAO;
import com.evil.DAO.IntegralDAO;
import com.evil.DAO.UserDAO;
import com.evil.Servlet.BaseServlet;
import com.google.gson.Gson;

/******************************************
 * 工程名：EdaSupport<br>
 * 包名：com.evil.Answer<br>
 * 时间：2016年8月31日 上午11:03:30<br>
 * 作者：白雨濃 evil<br>
 * 邮箱：evilbai@foxmail.com<br>
 * 内容：提交做完的答案<br>
 ******************************************/
public class AnswerOverItemServlet extends BaseServlet
{
    private String userPhone;
    private String imei;
    private int itemId;
    private int yesNum;
    private int noNum;
    private int sumFlow;
    private String type;

    @Override
    public void doPost()
    {
        userPhone = getParameter("phone");
        imei = getParameter("imei");
        itemId = getParameterInt("itemId");
        yesNum = getParameterInt("yes");
        noNum = getParameterInt("no");
        sumFlow = getParameterInt("sumFlow");
        type = getParameter("type");

        if (type.equals("SUBMIT"))
        {
            if (isOverTimes() == AnswerDAO.TIMES_NOMORE)
            {
                AnswerOverItemBean bean = new AnswerOverItemBean();
                bean.setPhone(userPhone);
                bean.setItemId(itemId);
                bean.setYesNum(yesNum);
                bean.setNoNum(noNum);
                bean.setSumFlow(sumFlow);

                submitNewItem(bean);
            }
            else
                print("MOREOVERTIMES");
        }
    }

    /**
     * 判断是否超过答题的限制数目,times++
     */
    private int isOverTimes()
    {
        return new AnswerDAO().isOverTimes(userPhone, true);
    }


    /**
     * 提交一个新的项目
     */
    private void submitNewItem(AnswerOverItemBean bean)
    {
        Object p = new AnswerOverItemDAO().insertNewItem(bean);

        if (p instanceof Integer)
        {
            int r = (Integer) p;

            if (r == AnswerOverItemDAO.SUCCESS)
            {
                /*成功后，更新用户积分*/
                if (new IntegralDAO().updateIntegral(userPhone, sumFlow))
                {
                    new IntegralDAO().updateIntegral_month_today(userPhone, sumFlow);
                    out.print("SUCCESS");
                }
                else
                    out.print("FAIL");
            }
            else if (r == AnswerOverItemDAO.FAIL)
                out.print("FAIL");
            else if (r == AnswerOverItemDAO.NULL)
                out.print("ERROR");
        }
        else if (p instanceof String)
        {
            String r = (String) p;

            System.out.println(r);

            out.print(r);
        }
        else if (p instanceof AnswerOverItemBean)
        {
            AnswerOverItemBean itemBean = (AnswerOverItemBean) p;
            out.print("ISOVER" + new Gson().toJson(itemBean));
        }
    }

}
